import React, { useState, useEffect } from 'react';
import { Button, Input, Label, Text, Spinner, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose } from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import { AuditLogService, AuditAction } from '@packages/shared';

// 角色接口
export interface Role {
  id: string;
  name: string;
  description: string;
  permissions: string[];
}

// 权限接口
export interface Permission {
  id: string;
  name: string;
  description: string;
  category: string;
}

// 预定义的系统角色
const defaultRoles: Role[] = [
  {
    id: 'admin',
    name: '主任',
    description: '拥有系统所有权限，可以编辑修改任何管理项目',
    permissions: [
      'user.create', 'user.read', 'user.update', 'user.delete',
      'role.assign', 'audit.view', 'audit.export', 'system.settings',
      'grade.create', 'grade.read', 'grade.update', 'grade.delete',
      'score.create', 'score.read', 'score.update', 'score.delete',
      'classroom.create', 'classroom.read', 'classroom.update', 'classroom.delete',
      'dashboard.view'
    ]
  },
  {
    id: 'user',
    name: '老师',
    description: '拥有基础操作权限，可以修改成绩和增加综合积分',
    permissions: [
      'user.read', 'audit.view',
      'grade.read', 'grade.update',
      'score.create', 'score.read', 'score.update',
      'classroom.read',
      'dashboard.view'
    ]
  },
  {
    id: 'guest',
    name: '学生',
    description: '仅拥有查看权限',
    permissions: [
      'user.read', 'grade.read', 'score.read',
      'classroom.read', 'dashboard.view'
    ]
  }
];

// 系统所有可用权限
const allPermissions: Permission[] = [
  // 用户管理权限
  { id: 'user.create', name: '创建用户', description: '可以添加新用户', category: '用户管理' },
  { id: 'user.read', name: '查看用户', description: '可以查看用户列表和信息', category: '用户管理' },
  { id: 'user.update', name: '编辑用户', description: '可以修改用户信息', category: '用户管理' },
  { id: 'user.delete', name: '删除用户', description: '可以删除用户', category: '用户管理' },
  { id: 'role.assign', name: '分配角色', description: '可以分配用户角色', category: '用户管理' },
  
  // 成绩管理权限
  { id: 'grade.create', name: '创建成绩', description: '可以添加新成绩记录', category: '成绩管理' },
  { id: 'grade.read', name: '查看成绩', description: '可以查看成绩列表', category: '成绩管理' },
  { id: 'grade.update', name: '修改成绩', description: '可以修改成绩记录', category: '成绩管理' },
  { id: 'grade.delete', name: '删除成绩', description: '可以删除成绩记录', category: '成绩管理' },
  
  // 综合积分权限
  { id: 'score.create', name: '创建积分', description: '可以添加综合积分记录', category: '综合积分' },
  { id: 'score.read', name: '查看积分', description: '可以查看综合积分记录', category: '综合积分' },
  { id: 'score.update', name: '修改积分', description: '可以修改综合积分记录', category: '综合积分' },
  { id: 'score.delete', name: '删除积分', description: '可以删除综合积分记录', category: '综合积分' },
  
  // 班级管理权限
  { id: 'classroom.create', name: '创建班级', description: '可以添加班级信息', category: '班级管理' },
  { id: 'classroom.read', name: '查看班级', description: '可以查看班级信息', category: '班级管理' },
  { id: 'classroom.update', name: '修改班级', description: '可以修改班级信息', category: '班级管理' },
  { id: 'classroom.delete', name: '删除班级', description: '可以删除班级信息', category: '班级管理' },
  
  // 系统权限
  { id: 'audit.view', name: '查看审计日志', description: '可以查看操作日志', category: '系统权限' },
  { id: 'audit.export', name: '导出审计日志', description: '可以导出日志文件', category: '系统权限' },
  { id: 'system.settings', name: '系统设置', description: '可以修改系统配置', category: '系统权限' },
  { id: 'dashboard.view', name: '查看仪表板', description: '可以查看系统仪表板', category: '系统权限' }
];

// 分类列表
const permissionCategories = [
  { id: 'user', name: '用户管理' },
  { id: 'grade', name: '成绩管理' },
  { id: 'score', name: '综合积分' },
  { id: 'classroom', name: '班级管理' },
  { id: 'system', name: '系统权限' }
];

// 组件定义和导出
export const PermissionAssignment = () => {
  const { session } = useSession();
  const [roles, setRoles] = useState<Role[]>([]);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [showAlert, setShowAlert] = useState(false);
  const [alert, setAlert] = useState('');
  const [showDialog, setShowDialog] = useState(false);

  // 从本地存储加载角色数据
  const loadRolesFromLocalStorage = () => {
    const savedRoles = localStorage.getItem('roles');
    return savedRoles ? JSON.parse(savedRoles) : defaultRoles;
  };

  // 保存角色数据到本地存储
  const saveRolesToLocalStorage = (roles: Role[]) => {
    localStorage.setItem('roles', JSON.stringify(roles));
  };

  // 初始化加载角色数据
  useEffect(() => {
    setRoles(loadRolesFromLocalStorage());
  }, []);

  // 处理角色选择
  const handleRoleSelect = (role: Role) => {
    setSelectedRole(role);
    setSelectedPermissions([...role.permissions]);
    setShowDialog(true);
  };

  // 保存角色权限更改
  const handleSave = async () => {
    if (!selectedRole || !session) return;

    setLoading(true);
    try {
      const updatedRoles = roles.map(role => 
        role.id === selectedRole.id 
          ? { ...role, permissions: selectedPermissions }
          : role
      );

      setRoles(updatedRoles);
      saveRolesToLocalStorage(updatedRoles);
      
      await AuditLogService.log(
        session.userId,
        session.userName,
        session.userRole,
        AuditAction.ROLE_ASSIGN,
        `更新角色 "${selectedRole.name}" 的权限配置`,
        true
      );
      
      setAlert('保存成功');
      setShowAlert(true);
      setShowDialog(false);
      
      // 3秒后隐藏提示
      setTimeout(() => {
        setShowAlert(false);
      }, 3000);
    } catch (error) {
      console.error('保存角色权限失败:', error);
      setAlert('保存失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 切换权限选择
  const togglePermission = (permissionId: string) => {
    setSelectedPermissions(prev => 
      prev.includes(permissionId)
        ? prev.filter(id => id !== permissionId)
        : [...prev, permissionId]
    );
  };

  // 获取权限名称
  const getPermissionName = (permissionId: string) => {
    const permission = allPermissions.find(p => p.id === permissionId);
    return permission ? permission.name : permissionId;
  };

  // 重置为默认权限
  const resetToDefault = async () => {
    if (!session) return;

    setLoading(true);
    try {
      setRoles(defaultRoles);
      saveRolesToLocalStorage(defaultRoles);
      
      await AuditLogService.log(
        session.userId,
        session.userName,
        session.userRole,
        AuditAction.ROLE_ASSIGN,
        '重置所有角色权限为默认值',
        true
      );
      
      setAlert('已重置为默认权限配置');
      setShowAlert(true);
      
      // 3秒后隐藏提示
      setTimeout(() => {
        setShowAlert(false);
      }, 3000);
    } catch (error) {
      console.error('重置权限失败:', error);
      setAlert('重置失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 按分类获取权限
  const getPermissionsByCategory = (category: string) => {
    return allPermissions.filter(permission => permission.category === category);
  };

  return (
    <div className="p-6 bg-white rounded-lg shadow-md">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-gray-800">权限分配管理</h1>
        <Button
          onClick={resetToDefault}
          className="bg-red-500 hover:bg-red-600 text-white"
          disabled={loading}
        >
          重置为默认配置
        </Button>
      </div>

      {showAlert && (
        <div className="mb-4 p-3 bg-blue-100 text-blue-800 rounded-lg animate-fade-in-out">
          <Text>{alert}</Text>
        </div>
      )}

      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-1/4">角色名称</TableHead>
              <TableHead className="w-1/4">描述</TableHead>
              <TableHead className="w-1/4">权限数量</TableHead>
              <TableHead className="w-1/4 text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {roles.map((role) => (
              <TableRow key={role.id}>
                <TableCell className="font-medium">{role.name}</TableCell>
                <TableCell>{role.description}</TableCell>
                <TableCell>{role.permissions.length}</TableCell>
                <TableCell className="text-right">
                  <Button
                    onClick={() => handleRoleSelect(role)}
                    className="bg-blue-500 hover:bg-blue-600 text-white"
                  >
                    编辑权限
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* 权限编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="sm:max-w-[700px]">
          <DialogHeader>
            <DialogTitle>编辑角色权限 - {selectedRole?.name}</DialogTitle>
            <DialogDescription>
              为角色分配或移除系统权限
            </DialogDescription>
          </DialogHeader>
          <div className="mt-4 space-y-4">
            {permissionCategories.map((category) => {
              const categoryPermissions = getPermissionsByCategory(category.name);
              return (
                <div key={category.id} className="border rounded-lg p-4">
                  <h3 className="font-semibold text-gray-700 mb-2">{category.name}</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                    {categoryPermissions.map((permission) => (
                      <div key={permission.id} className="flex items-center space-x-2">
                        <input
                          type="checkbox"
                          id={permission.id}
                          checked={selectedPermissions.includes(permission.id)}
                          onChange={() => togglePermission(permission.id)}
                          className="rounded border-gray-300 text-blue-500 focus:ring-blue-500"
                        />
                        <label
                          htmlFor={permission.id}
                          className="text-sm text-gray-700 cursor-pointer"
                        >
                          {permission.name} - {permission.description}
                        </label>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="secondary">取消</Button>
            </DialogClose>
            <Button onClick={handleSave} disabled={loading}>
              {loading ? (
                <>
                  <Spinner className="mr-2 h-4 w-4" />
                  保存中...
                </>
              ) : (
                '保存更改'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}